﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonExtensions.IEnumerableExtensions;
using CommonExtensions.ObjectExtensions;
using CommonExtensions.StringExtensions;
using StructureMap;

namespace DBMigrator.Core.DbObjects.Data.What
{
    public class WhatColumnList : List<IWhatColumn>, IWhatColumnList
    {
        public void AddColumns(params string[] columnNames)
        {
            AddColumnsHelper(null, columnNames);
        }

        public void AddTableColumns(string tableName, params string[] columnNames)
        {
            if (tableName.IsBlank())
                throw new ArgumentNullException("tableName");

            AddColumnsHelper(tableName, columnNames);
        }

        private void AddColumnsHelper(string tableName, IEnumerable<string> columnNames)
        {
            if (columnNames.IsNull())
                throw new ArgumentNullException("columnNames");
            if (columnNames.IsEmpty())
                throw new ArgumentOutOfRangeException("columnNames", "columnNames cannot be blank");
            if (columnNames.Any(c => c.IsBlank()))
                throw new ArgumentException("Column names cannot be null or empty", "columnNames");

            AddRange(columnNames.Select(columnName => CreateColumn(tableName, columnName)));
        }

        public void AddAllTableColumns(string tableName)
        {
            AddTableColumns(tableName, WhatConstants.AllIdentifier);
        }

        public void AddAllColumns()
        {
            Add(CreateColumn(WhatConstants.AllIdentifier, WhatConstants.AllIdentifier));
        }

        private static IWhatColumn CreateColumn(string tableName, string columnName)
        {
            return ObjectFactory.With("tableName").EqualTo(tableName).With("columnName").EqualTo(columnName)
                .GetInstance<IWhatColumn>();
        }
    }
}